package business;

import java.util.List;

import javax.xml.bind.JAXBException;

import org.example.bankdb.AccountInfo;
import org.example.bankdb.BanKInfo;


public class BankController {	
	private static BankController controller;
	
	public static BankController getController(){
		if (controller == null){
			try {
				controller= new BankController();
			} catch (JAXBException e) {
				e.printStackTrace();
			}		
		}
		
		return controller;
	}
	
	private BankRepository repository;
	
	
	public BankController() throws JAXBException{
		repository = new BankRepository();
	}
	
	public boolean createAccount(String accountID, int amount) throws JAXBException{
		AccountInfo vAccount = new AccountInfo();
		vAccount.setAccountID(accountID);
		vAccount.setAmount(amount);
		BanKInfo banKInfo = repository.GetBank();
		banKInfo.getAccount().add(vAccount);
		repository.SaveBank(banKInfo);
		return true;
	}
		
	public int queryAccount(String accountID) throws JAXBException{
		AccountInfo accountInfo = this.GetAccount(accountID, this.repository.GetBank());
		
		if (accountInfo != null){			
			return accountInfo.getAmount();			
		}
		
		return -1;
	}
	
	private AccountInfo GetAccount(String accountID, BanKInfo banKInfo){
		if (banKInfo != null){
			List<AccountInfo> accounts = banKInfo.getAccount();
			for(AccountInfo account : accounts){
				if (account.getAccountID().equals(accountID)){
					return account;
				}
			}
		}
		
		return null;
	}
	
	public boolean transfer(String accountID1, String accountID2, int amount) throws JAXBException{
		BanKInfo bankInfo =  repository.GetBank();
		AccountInfo account1 = this.GetAccount(accountID1, bankInfo);
		AccountInfo account2 = this.GetAccount(accountID2, bankInfo);
		boolean success = false;
		if (account1 != null && account2 != null) {
			
			if (account1.getAmount() - amount > 0){
				account1.setAmount(account1.getAmount() - amount);
				account2.setAmount(account2.getAmount() + amount);
				
				repository.SaveBank(bankInfo);
				success = true;
			}
		}
		
		return success;
	}
}
